package com.srb.core.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.srb.core.mapper.DictMapper;
import com.srb.core.pojo.dto.ExcelDictDTO;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@NoArgsConstructor
public class ExcelDictDTOListener  extends AnalysisEventListener<ExcelDictDTO> {

    private DictMapper dictMapper;

    //数据列表
    List<ExcelDictDTO> list= new ArrayList<>();

    //没隔5条记录存储一次数据
    private static final int BATCH_COUNT = 5;

    public ExcelDictDTOListener(DictMapper dictMapper){
        this.dictMapper=dictMapper;
    }

    @Override
    public void invoke(ExcelDictDTO data, AnalysisContext analysisContext) {
        log.info("解析到一条记录：{}"+data);

        //将数据存入数据列表
        list.add(data);
        if (list.size()>=BATCH_COUNT){
            saveData();
            list.clear();
        }
        //调用mapper层的save方法
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
        log.info("所有数据解析完成！");
    }

    private void saveData(){
        log.info("{}条数据被存储到数据库...",list.size());
        //调用mapper层save方法
        dictMapper.insertBatch(list);
        log.info("{}条数据存储到数据库成功。",list.size());
    }
}
